package utils

import (
	"crypto/tls"
	"fmt"
	"net/smtp"
	"strings"

	"github.com/spf13/viper"
)

func SendEmail(to string, subject string, body string) error {
	// 从环境变量获取邮箱配置
	from := viper.GetString("SMTP_FROM")
	password := viper.GetString("SMTP_PASSWORD")
	smtpHost := viper.GetString("SMTP_HOST")
	smtpPort := viper.GetString("SMTP_PORT")

	if from == "" || password == "" || smtpHost == "" || smtpPort == "" {
		return fmt.Errorf("missing email configuration")
	}

	msg := []byte(fmt.Sprintf("To: %s\r\n"+
		"Subject: %s\r\n"+
		"\r\n"+
		"%s\r\n", to, subject, body))

	// 163邮箱的SMTP服务器地址和端口
	if strings.HasSuffix(from, "@163.com") {
		smtpHost = "smtp.163.com"
		smtpPort = "465" // 163邮箱推荐使用465端口(SSL)

		// 创建TLS配置
		tlsConfig := &tls.Config{
			InsecureSkipVerify: true,
			ServerName:         smtpHost,
		}

		// 创建SSL连接
		conn, err := tls.Dial("tcp", smtpHost+":"+smtpPort, tlsConfig)
		if err != nil {
			return fmt.Errorf("failed to create SSL connection: %v", err)
		}
		defer conn.Close()

		client, err := smtp.NewClient(conn, smtpHost)
		if err != nil {
			return fmt.Errorf("failed to create SMTP client: %v", err)
		}
		defer client.Close()

		// 认证
		auth := smtp.PlainAuth("", from, password, smtpHost) // password应该是163邮箱的授权码
		if err := client.Auth(auth); err != nil {
			return fmt.Errorf("failed to authenticate: %v", err)
		}

		// 设置发件人和收件人
		if err := client.Mail(from); err != nil {
			return fmt.Errorf("failed to set sender: %v", err)
		}
		if err := client.Rcpt(to); err != nil {
			return fmt.Errorf("failed to set recipient: %v", err)
		}

		// 发送邮件内容
		w, err := client.Data()
		if err != nil {
			return fmt.Errorf("failed to create message writer: %v", err)
		}
		_, err = w.Write(msg)
		if err != nil {
			return fmt.Errorf("failed to write message: %v", err)
		}
		err = w.Close()
		if err != nil {
			return fmt.Errorf("failed to close message writer: %v", err)
		}

		return client.Quit()
	}

	auth := smtp.PlainAuth("", from, password, smtpHost)

	err := smtp.SendMail(smtpHost+":"+smtpPort, auth, from, []string{to}, msg)
	if err != nil {
		return fmt.Errorf("failed to send email: %v", err)
	}

	return nil
}
